<template>
  <div class="edit-page-container">
    <!-- 面包屑导航 -->
<!--    <Breadcrumb :items="breadcrumbItems" />-->

    <div class="content-container">
      <div class="page-title">
        <h3>{{ isEditMode ? '编辑数据' : '新增数据' }}</h3>
      </div>

      <!-- 表单卡片 -->
      <el-card class="form-card">
        <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="80px"
            class="vertical-form"
        >
          <!-- 表单字段 -->
          <el-form-item label="名称" prop="username">
            <el-input v-model="formData.username" placeholder="请输入名称" style="width: 300px;"/>
          </el-form-item>
           <!-- <el-form-item label="用户ID" prop="userId">
            <el-input v-model="formData.userId" placeholder="请输入名称" />
          </el-form-item> -->

          <el-form-item label="密码" prop="password">
            <el-input v-model="formData.password" placeholder="请输入名称" style="width: 300px;"/>
          </el-form-item>

          <!-- <el-form-item label="真实姓名" prop="userRealName">
            <el-input v-model="formData.userRealName" placeholder="请输入名称" />
          </el-form-item> -->

          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入名称" style="width: 300px;"/>
          </el-form-item>

           <!-- <el-form-item label="points" prop="points">
            <el-input v-model="formData.points" placeholder="请输入名称" />
          </el-form-item> -->
          <!-- <el-form-item label="isLock" prop="isLock">
            <el-input v-model="formData.isLock" placeholder="请输入名称" />
          </el-form-item> -->


         

<!-- 
          <el-form-item label="deptName" prop="deptName">
            <el-input v-model="formData.deptName" placeholder="请输入名称" />
          </el-form-item> -->

          <!-- <el-form-item label="roleId" prop="roleId">
            <el-input v-model="formData.roleId" placeholder="请输入名称" />
          </el-form-item> -->

          <!-- <el-form-item label="性别" prop="userSex">
            <el-select v-model="formData.userSex" placeholder="请选择状态">
              <el-option label="男性" value="男" />
              <el-option label="女性" value="女" />
            </el-select>
          </el-form-item> -->

<!--          <el-form-item label="描述" prop="description">-->
<!--            <el-input-->
<!--                v-model="formData.description"-->
<!--                placeholder="请输入描述"-->
<!--                type="textarea"-->
<!--                :rows="3"-->
<!--            />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="分类" prop="category">-->
<!--            <el-select v-model="formData.category" placeholder="请选择分类">-->
<!--              <el-option label="分类A" value="category_a" />-->
<!--              <el-option label="分类B" value="category_b" />-->
<!--              <el-option label="分类C" value="category_c" />-->
<!--            </el-select>-->
<!--          </el-form-item>-->

<!--          <el-form-item label="日期" prop="date">-->
<!--            <el-date-picker-->
<!--                v-model="formData.date"-->
<!--                type="date"-->
<!--                placeholder="选择日期"-->
<!--            />-->
<!--          </el-form-item>-->

<!--          <el-form-item label="附件" prop="attachment">-->
<!--            <el-upload-->
<!--                action="#"-->
<!--                :show-file-list="false"-->
<!--                :on-success="handleUploadSuccess"-->
<!--                class="upload-btn"-->
<!--            >-->
<!--              <el-button type="primary" size="small">上传文件</el-button>-->
<!--            </el-upload>-->
<!--            <span v-if="formData.attachment" class="uploaded-file">-->
<!--              {{ formData.attachment.name }}-->
<!--              <el-button-->
<!--                  type="text"-->
<!--                  size="mini"-->
<!--                  @click="removeAttachment"-->
<!--                  class="ml-2"-->
<!--              >-->
<!--                移除-->
<!--              </el-button>-->
<!--            </span>-->
<!--          </el-form-item>-->

          <!-- 表单操作按钮 -->

        </el-form>
        <el-form-item class="form-actions">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="saveData">保存</el-button>
        </el-form-item>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import Breadcrumb from "@/components/breadcrumb/index.vue";
import api from "@/api/userLogin.js";
import {ElMessage} from "element-plus";
 import axios from 'axios';
const router = useRouter();
const route = useRoute();

// 表单引用
const formRef = ref(null);

// 表单数据
let formData = ref({
  // formData:{},
  // userId:'',
  username:'',
  password:'',
  // role:'',
  phone:'',
  // points:'',
  // userEmail:'',
  isLock:'',
  // deptId:'',
  // deptName:'',
  // roleId:'',
  createTime:'',
  amendTime:'',
});
let loading =ref(false);
// 表单验证规则
const rules = reactive({
});

// 面包屑数据
const breadcrumbItems = [
  { label: '首页', path: '/' },
  { label: '数据管理', path: '/data' },
  // { label: isEditMode ? '编辑数据' : '新增数据' }
];

// 判断是否为编辑模式
const isEditMode = ref("");

// 模拟获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      userId: route.params.id
    };
    const response = await api.findById(params);
    if (response.code == 200 ) { // 根据你的API设计调整
      debugger
      formData.value = response.data;
      console.log(" formData.value+", formData)
    } else {
      // API返回了错误码
      throw new Error(response.message || '获取数据失败');
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    // 友好的错误提示
    ElMessage.error({
      message: error.message || '加载数据失败，请稍后重试',
      duration: 3000
    });
    // 重置数据防止显示旧数据
    formData.value = [];
  } finally {
    loading.value = false;
  }
};
const saveData = async () => {
  // console.log("表单数据2", formData);
   console.log("表单数据", formData);
  let response;   
  // 表单验证
  formRef.value.validate(async valid => {
    if (valid) {
      // 模拟API请求
      // const apiMethod = isEditMode.value ? 'PUT' : 'POST';
      if (isEditMode.value) {
        
        response = await api.update(formData.value);
      }else{
        response = await api.insert(formData.value);
      }
      // 显示成功消息
      ElMessage.success(isEditMode.value ? '数据更新成功' : '数据创建成功');
      // 返回列表页
      router.push('/user');
    }
  });
};

// 取消编辑
const cancelEdit = () => {
  router.push("/user");
};
// 移除附件
// 初始化数据
onMounted(() => {
  console.log(route.params,"route.params")
  if (route.params.id !=null ||route.params.id !=undefined ) {
    isEditMode.value = true;
    const id = route.params.id;
    fetchData(id);
  }else{
    isEditMode.value = false;
  }
});

// // 监听路由变化，更新面包屑
// watch(
//     () => route.params.id,
//     (newId) => {
//       console.log("newId",newId)
//       isEditMode.value = !!newId;
//       breadcrumbItems[2].label = isEditMode.value ? '编辑数据' : '新增数据';
//
//       if (isEditMode.value) {
//         fetchData(newId);
//       } else {
//         // 重置表单
//         Object.assign(formData, {
//           id: null,
//           name: '',
//           description: '',
//           status: 'active',
//           category: 'category_a',
//           date: null,
//           attachment: null,
//         });
//       }
//     }
// );
</script>

<style scoped>
.edit-page-container {
  padding: 20px;
}

.content-container {
  margin-top: 20px;
}

.page-title {
  margin-bottom: 20px;
}

.form-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}
.el-form-item {
  align-items: center;
}
.edit-form {
  margin-top: 20px;
  display: grid;
  grid-template-columns: 50% 50%;
}

.form-actions {
  margin-top: 30px;
  text-align: right;
}
.upload-btn {
  display: inline-block;
  vertical-align: middle;
}
:deep(.el-form-item__content) {
  justify-content: center !important;
}
.uploaded-file {
  margin-left: 10px;
  display: inline-block;
  vertical-align: middle;
}
</style>
